package controllers;

import java.util.Arrays;
import java.util.List;

import play.i18n.Messages;
import play.mvc.Controller;
import play.mvc.With;
import client.RestException;
import client.YouGoClient;

import com.ineatconseil.yougo.dto.RequestTypeDto;

@With(Secure.class)
public class ManageRequestType extends AbstractConroller {

	public static YouGoClient client = new YouGoClient();

	public static void index() throws RestException {
		List<RequestTypeDto> requestType = getRequestTypeDto();
		render(requestType);
	}

	public static void deleteRequestType(Long requestId) throws RestException {

		client.deleteRequestTypeDto(requestId);
		flash.success(Messages.get("managerequesttype.success.delete"));
		index();
	}

	public static void edit(Long requestId) throws RestException {
		RequestTypeDto requestType = new RequestTypeDto();
		if (requestId != null) {
			requestType = client.getRequestTypeDto(requestId);
			render(requestType);
		} else {
			render();
		}
	}

	/**
	 * Crée ou modifie un requesttypeDTO ==> si id == null => création
	 * 
	 * @param id
	 * @param description
	 * @throws RestException
	 */
	public static void save(Long id, String description) throws RestException {
		if (description.equals("")) {
			flash.error("La description ne peut être vide");
			edit(id);
		}
		if (id == null) {
			RequestTypeDto requestTypeDto = new RequestTypeDto();
			requestTypeDto.setDescription(description);
			client.postRequestTypeDto(requestTypeDto);
			flash.success(Messages.get("managerequesttype.success.createupdate"));
		} else {
			RequestTypeDto requestTypeDto = client.getRequestTypeDto(id);
			requestTypeDto.setDescription(description);
			client.putTypeDto(requestTypeDto);
			flash.success(Messages.get("managerequesttype.success.createupdate"));
		}
		index();
	}

}
